import React, { useState, useRef, useEffect } from "react";
import { Card, Row, Col, Upload, Button, message, Form, Input, Select } from "antd";
import {
  UploadOutlined,
  PlayCircleOutlined,
  DeleteOutlined,
  HistoryOutlined
} from "@ant-design/icons";
import * as echarts from "echarts";
import { api } from "../../api";
import "./style.scss";
import { useSelector, useDispatch } from 'react-redux';
import {
  setTopologyData,
  setHistoryTopologies,
  clearTopologyData
} from '../../store/slices/networkSlice';

const { Option } = Select;

const TopologyBuilder = () => {
  // 使用Redux存储状态
  const dispatch = useDispatch();
  const { topologyData, historyTopologies } = useSelector(state => state.network);

  // 本地状态只保留UI相关的状态
  const [loading, setLoading] = useState(false);
  const [selectedTopologyId, setSelectedTopologyId] = useState(null); // 添加选中的历史拓扑ID状态
  const chartRef = useRef(null);// ECharts 容器引用
  const chartInstance = useRef(null); // 保存图表实例的引用
  const [form] = Form.useForm(); // 添加表单引用

  useEffect(() => {
    if (topologyData) {
      renderTopology(topologyData); // 渲染拓扑图
      // 重置表单
      form.resetFields();
    }

    // 组件卸载时销毁图表实例
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
    };
  }, [topologyData, form]);

  // 上传文件并绘制拓扑图
  const handleFileUpload = async (file) => {
    try {
      setLoading(true);

      // 检查文件类型
      if (file.type !== 'application/json') {
        message.error('请上传JSON格式的文件');
        setLoading(false);
        return false;
      }

      // 先读取文件内容，确保是有效的JSON
      const fileContent = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => resolve(e.target.result);
        reader.onerror = e => reject(e);
        reader.readAsText(file);
      });

      let jsonData;
      try {
        jsonData = JSON.parse(fileContent);
        // 验证JSON结构
        if (!jsonData.nodes || !jsonData.links || !Array.isArray(jsonData.nodes) || !Array.isArray(jsonData.links)) {
          message.error('文件格式不正确，缺少nodes或links数组');
          setLoading(false);
          return false;
        }
      } catch (error) {
        console.error("文件解析错误:", error);
        message.error("文件格式错误，请上传正确的 JSON 文件");
        setLoading(false);
        return false;
      }

      // 上传文件到后端
      const res = await api.loadTopology(file);

      if (res.code === 0 || res.code === 200) {
        message.success(res.msg || "文件上传成功");
        // 使用已解析的JSON数据更新状态
        dispatch(setTopologyData(jsonData));
      } else {
        message.error(res.msg || "文件上传失败");
      }
    } catch (error) {
      console.error("文件上传错误:", error);
      message.error("文件上传到后端失败");
    } finally {
      setLoading(false);
    }
    return false; // 阻止默认上传行为
  };

  // 加载默认拓扑
  const handleDefaultLoad = async () => {
    try {
      setLoading(true);
      const res = await api.loadDefaultTopology();

      if (res.code === 0 || res.code === 200) {
        message.success("默认拓扑加载成功");

        // 使用后端返回的数据，如果没有则使用前端默认数据
        const defaultTopology =  {
          nodes: [
            { name: "attacker1", ip: "192.168.1.101", subnet: "255.255.255.0", type: "attacker" },
            { name: "server1", ip: "192.168.1.102", subnet: "255.255.255.0", type: "server" },
            { name: "server2", ip: "192.168.1.103", subnet: "255.255.255.0", type: "server" },
          ],
          links: [
            { source: "attacker1", target: "server1", bandwidth: "10mbps", delay: "10ms" },
            { source: "server1", target: "server2", bandwidth: "5mbps", delay: "20ms" },
          ],
        };

      } else {
        message.error(res.msg || "加载默认拓扑失败");
      }
    } catch (error) {
      console.error("加载默认拓扑错误:", error);
      message.error("加载默认拓扑失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取历史拓扑列表
  const fetchHistoryTopologies = async () => {
    try {
      setLoading(true);
      const res = await api.getTopologyHistory();
      if (res.code === 0 || res.code === 200) {
        // 确保数据结构正确
        const historyData = res.data.data || [];
        dispatch(setHistoryTopologies(historyData));
        console.log("获取历史拓扑列表成功:", historyData);
      } else {
        message.error(res.msg || "获取历史拓扑列表失败");
      }
    } catch (error) {
      console.error("获取历史拓扑列表错误:", error);
      message.error("获取历史拓扑列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 组件挂载时获取历史拓扑列表
    fetchHistoryTopologies();
  }, []);

  // 选择历史拓扑
  const handleSelectTopology = (topologyId) => {
    console.log("选择历史拓扑:", topologyId);
    setSelectedTopologyId(topologyId);
  };

  // 加载历史拓扑
  const handleHistoryLoad = async () => {
    if (!selectedTopologyId) {
      message.warning("请先选择一个历史拓扑");
      return;
    }
    try {
      setLoading(true);
      console.log("加载历史拓扑:", selectedTopologyId);
      const res = await api.loadHistoryTopology(selectedTopologyId);

      if (res.code === 0 || res.code === 200) {
        // 正确的数据结构判断
        const topologyData = res.data.data || {};
        if (topologyData.nodes && Array.isArray(topologyData.nodes) &&
            topologyData.links && Array.isArray(topologyData.links)) {
          dispatch(setTopologyData(topologyData));
          message.success("历史拓扑加载成功");
        } else {
          message.warning("拓扑数据结构不正确，请检查");
          console.error("拓扑数据结构:", topologyData);
        }
      } else {
        message.error(res.msg || "加载历史拓扑失败");
      }
    } catch (error) {
      console.error("加载历史拓扑错误:", error);
      message.error("加载历史拓扑失败");
    } finally {
      setLoading(false);
    }
  };

  // 清理网络
  const handleClearNetwork = async () => {
    try {
      setLoading(true);
      const res = await api.clearNetwork();
      if (res.code === 0 || res.code === 200) {
        message.success(res.msg || "网络清理成功");
        dispatch(clearTopologyData()); // 清空前端拓扑图
      } else {
        message.error(res.msg || "清理网络失败");
      }
    } catch (error) {
      console.error("清理网络错误:", error);
      message.error("清理网络失败");
    } finally {
      setLoading(false);
    }
  };

  // 执行攻击
  const handleAttack = async (values) => {
    try {
      setLoading(true);
      // 转换为后端需要的格式
      const attackData = {
        attackType: parseInt(values.attackType),
        attackers: values.attackers,
        targets: values.targets
      };

      console.log("攻击数据:", attackData);

      const res = await api.executeAttack(attackData);
      if (res.code === 0 || res.code === 200) {
        message.success(res.msg || "攻击执行成功");
      } else {
        message.error(res.msg || "攻击执行失败");
      }
    } catch (error) {
      console.error("攻击执行错误:", error);
      message.error("攻击执行失败");
    } finally {
      setLoading(false);
    }
  };

  // 渲染拓扑图
  const renderTopology = (data) => {
    if (!chartRef.current) return;

    // 如果已经有图表实例，先销毁
    if (chartInstance.current) {
      chartInstance.current.dispose();
    }

    // 创建新的图表实例
    const chart = echarts.init(chartRef.current);
    chartInstance.current = chart;

    // 确保nodes和links是数组
    const nodes = Array.isArray(data.nodes) ? data.nodes.map((node) => ({
      id: node.name,
      name: node.name,
      category: node.type === "attacker" ? 0 : 1,
      symbol: node.type === "attacker"
        ? "path://M512 0C229.23 0 0 229.23 0 512s229.23 512 512 512S794.77 0 512 0z m0 960C264.6 960 64 759.4 64 512S264.6 64 512 64s448 200.6 448 448-200.6 448-448 448z"
        : "path://M256 64h512c35.35 0 64 28.65 64 64v768c0 35.35-28.65 64-64 64H256c-35.35 0-64-28.65-64-64V128c0-35.35 28.65-64 64-64z m0 64v768h512V128H256z m128 128h256v64H384v-64z m0 128h256v64H384v-64z m0 128h256v64H384v-64z",
      symbolSize: 60,
      itemStyle: {
        color: node.type === "attacker" ? "#ff4d4f" : "#1890ff",
      },
      label: {
        show: true,
        formatter: node.name,
        fontSize: 12,
        color: "#fff",
      },
      info: `IP: ${node.ip}<br/>子网: ${node.subnet}`,
    })) : [];

    const links = Array.isArray(data.links) ? data.links.map((link) => ({
      source: link.source,
      target: link.target,
      info: `带宽: ${link.bandwidth}<br/>延迟: ${link.delay}`,
    })) : [];

    const option = {
      tooltip: {
        trigger: "item",
        formatter: (params) => {
          if (params.dataType === "node") {
            return `名称: ${params.data.name}<br/>${params.data.info}`;
          } else if (params.dataType === "edge") {
            return `连接信息: ${params.data.info}`;
          }
        },
      },
      legend: [
        {
          data: ["攻击者", "服务器"],
          textStyle: {
            color: "#fff",
          },
        },
      ],
      series: [
        {
          type: "graph",
          layout: "force",
          roam: true,
          label: {
            show: true,
            position: "right",
            formatter: "{b}",
          },
          force: {
            repulsion: 1000,
          },
          data: nodes,
          links: links,
          categories: [
            { name: "攻击者" },
            { name: "服务器" },
          ],
        },
      ],
      backgroundColor: "#1f1f1f",
    };

    chart.setOption(option);
    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      chart.resize();
    };

    window.addEventListener('resize', handleResize);

    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      chart.dispose();
    };
  };

  // 获取攻击者列表
  const getAttackers = () => {
    if (!topologyData || !Array.isArray(topologyData.nodes)) return [];
    return topologyData.nodes
      .filter(node => node.type === "attacker")
      .map(node => node.name);
  };

  // 获取服务器列表（被攻击者）
  const getServers = () => {
    if (!topologyData || !Array.isArray(topologyData.nodes)) return [];
    return topologyData.nodes
      .filter(node => node.type === "server")
      .map(node => node.name);
  };

  // 攻击类型列表
  const attackTypes = [
    { value: 1, label: "DDoS 攻击" },
    { value: 2, label: "DNS 欺骗" },
    { value: 3, label: "ARP 欺骗" },
    { value: 4, label: "SYN 洪水攻击" },
    { value: 5, label: "HTTP 洪水攻击" },
    { value: 6, label: "Slowloris 攻击" },
    { value: 7, label: "组合攻击" }
  ];

  return (
    <Row gutter={[16, 16]}>
      <Col span={12}>
        <Card title="文件管理" bordered loading={loading}>
          <div className="file-management">
            {/* 历史拓扑选择器 */}
            <Select
              className="history-select"
              style={{ width: "100%", marginBottom: "16px" }}
              placeholder="选择历史拓扑"
              onChange={handleSelectTopology}
              value={selectedTopologyId}
              loading={loading}
              allowClear
            >
              {Array.isArray(historyTopologies) && historyTopologies.map(item => (
                <Option key={item.id} value={item.id}>
                  {item.name} - {new Date(item.createTime).toLocaleString()}
                </Option>
              ))}
            </Select>

            {/* 文件操作按钮组 */}
            <div className="button-group">
              <Button
                icon={<HistoryOutlined />}
                onClick={handleHistoryLoad}
                loading={loading}
                disabled={!selectedTopologyId}
                style={{ marginBottom: "16px" }}
              >
                加载历史拓扑
              </Button>
              <Upload
                customRequest={({ file }) => handleFileUpload(file)}
                showUploadList={false}
                accept=".json"
              >
                <Button icon={<UploadOutlined />} loading={loading}>
                  上传拓扑文件
                </Button>
              </Upload>
              <Button
                icon={<HistoryOutlined />}
                onClick={handleDefaultLoad}
                loading={loading}
              >
                加载默认拓扑
              </Button>
            </div>
          </div>
        </Card>
      </Col>

      <Col span={12}>
        <Card title="网络操作" bordered loading={loading}>
          <Form form={form} onFinish={handleAttack}>
            <Form.Item
              name="attackType"
              label="攻击类型"
              rules={[{ required: true, message: "请选择攻击类型" }]}
            >
              <Select placeholder="请选择攻击类型">
                {attackTypes.map(type => (
                  <Option key={type.value} value={type.value}>
                    {type.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="attackers"
              label="攻击者"
              rules={[{ required: true, message: "请选择攻击者" }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择攻击者"
                disabled={!topologyData}
              >
                {getAttackers().map(name => (
                  <Option key={name} value={name}>
                    {name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="targets"
              label="攻击目标"
              rules={[{ required: true, message: "请选择攻击目标" }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择攻击目标"
                disabled={!topologyData}
              >
                {getServers().map(name => (
                  <Option key={name} value={name}>
                    {name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Button
              type="primary"
              htmlType="submit"
              icon={<PlayCircleOutlined />}
              loading={loading}
              disabled={!topologyData}
            >
              执行攻击
            </Button>
          </Form>
          <Button
            style={{ marginTop: "10px" }}
            icon={<DeleteOutlined />}
            onClick={handleClearNetwork}
            loading={loading}
            disabled={!topologyData}
          >
            清理网络
          </Button>
        </Card>
      </Col>

      <Col span={24}>
        <Card title="网络拓扑图" bordered>
          <div ref={chartRef} style={{ width: "100%", height: "500px" }}></div>
        </Card>
      </Col>
    </Row>
  );
};

export default TopologyBuilder;
